﻿Imports System.Net
Imports System.IO
Imports System.Drawing.Image
Imports System.Xml
Imports System.Text
Imports System.Environment
Imports System.Web.HttpUtility
Imports System.Text.RegularExpressions
Imports ibnCredentials.FtpCreds 'external dll for credentials

Public Class Form1
    Friend settingsFile As String = (GetFolderPath(SpecialFolder.LocalApplicationData) & "\theHTPC\" & "settings.xml") 'location of settings file
    Dim lastIndex = 0
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Text = "theHTPC.net IBN People Project Uploader " & Application.ProductVersion
        'first load of application it is disabled.
        btnGetList.Enabled = False
        picboxAddImg.Controls.Add(picboxWorkImg)
        picboxWorkImg.Location = New Drawing.Point(5, 5)
        picboxAddImg.AllowDrop = True
        SearchGoogleImagesToolStripMenuItem.Checked = True
        SearchYahooImagesToolStripMenuItem.Checked = False
        SearchBingToolStripMenuItem.Checked = False
        WebBrowser1.ScriptErrorsSuppressed = True
        lblImgRes.BackColor = Color.Transparent
        btnEzAdd.Visible = False

        Try
            If File.Exists(settingsFile) = True Then 'check for settings file and password
                Dim doc As New XmlDocument
                doc.Load(settingsFile)
                If String.Compare(Password.GetHashCode.ToString().ToString, doc.SelectSingleNode("Check/AppPass").InnerText, False) = 0 Then
                    btnGetList.Enabled = True
                    btnGetList.Enabled = True
                    'if unlock successful, check for update
                    Try 'check for previous update "old" file.  delete if exists.
                        If File.Exists(Application.StartupPath & "\ibnuploader.old") = True Then
                            File.Delete(Application.StartupPath & "\ibnuploader.old")
                        End If
                    Catch ex As Exception
                        MessageBox.Show(ex.Message)
                    End Try
                    Dim url As New System.Uri("http://update.thehtpc.net/ibnuploader/UpdateVersion.txt") 'update check on application launch.  ignore errors.'
                    Dim req As WebRequest
                    req = WebRequest.Create(url)
                    Dim resp As WebResponse
                    resp = req.GetResponse()
                    resp.Close()
                    req = Nothing
                    webBrwsStartup.Navigate(url)
                End If
            Else
                Directory.CreateDirectory(GetFolderPath(SpecialFolder.LocalApplicationData) & "\theHTPC") 'if directory doesn't exist, create it and show the password form
                Form2.ShowDialog()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Me.Close()
        End Try
    End Sub

    Public Sub webBrwsStartup_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles webBrwsStartup.DocumentCompleted
        Try
            Dim m As Match = Regex.Match(webBrwsStartup.DocumentText, "<PRE>(?<version>(.*?))</PRE>") 'regex for version in text file
            If m.Success = True Then
                If Application.ProductVersion <> m.Groups("version").Value Then 'if versions do not match show update available dialog
                    Form4.ShowDialog()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnGetList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetList.Click
        'stuff to do after list is refreshed.  pushes the user to the necessary order of events.
        lstboxCast.Items.Clear()
        btnGetList.Enabled = False
        btnSelectImg.Enabled = False
        btnAddImg.Enabled = False
        btnSubmitImg.Enabled = False
        bgwLoadList.RunWorkerAsync()
    End Sub

    Private Sub bgwLoadList_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwLoadList.DoWork
        Dim sr1 As StreamReader = Nothing
        Try
            'Get the items in the new folder and put it in a list of string
            Dim newList As New List(Of String) 'this will hold all folder names in the new folder
            Dim sr2 As StreamReader = Nothing
            Dim fwrget2 As FtpWebRequest = FtpWebRequest.Create("ftp://thehtpc.net/new/")
            fwrget2.KeepAlive = False
            fwrget2.Credentials = New NetworkCredential(FTPusername, FTPpassword)
            fwrget2.Method = WebRequestMethods.Ftp.ListDirectory
            Dim myEncoding As Encoding
            myEncoding = System.Text.Encoding.GetEncoding(1252)
            sr2 = New StreamReader(fwrget2.GetResponse().GetResponseStream(), myEncoding)
            Dim str2 As String = sr2.ReadLine
            Try
                While String.IsNullOrEmpty(str2) = False
                    'adding each folder name to the list of string to check against
                    newList.Add(str2)
                    str2 = sr2.ReadLine
                End While
            Finally
                If Not sr2 Is Nothing Then
                    sr2.Close()
                    sr2.Dispose()
                End If
            End Try

            'Now get the list that needs actor images, you can use the same ftpwbrequest varibales
            'but lets just use the ones you have set already
            Dim fwrget1 As FtpWebRequest = FtpWebRequest.Create("ftp://thehtpc.net/old/")
            fwrget1.KeepAlive = False
            fwrget1.Credentials = fwrget2.Credentials
            fwrget1.Method = WebRequestMethods.Ftp.ListDirectory
            myEncoding = System.Text.Encoding.GetEncoding(1252)
            sr1 = New StreamReader(fwrget1.GetResponse().GetResponseStream(), myEncoding)

            Dim str1 As String = sr1.ReadLine

            While String.IsNullOrEmpty(str1) = False
                'check if the newList contins this name already, if not, add it to the listbox
                'If newList.Contains(str1) = False Then addActor(str1)
                If newList.Contains(str1) = False Then bgwLoadList.ReportProgress(0, str1)
                str1 = sr1.ReadLine
            End While

        Catch ex As Exception
            MessageBox.Show("ERROR: " & ex.Message & vbCrLf)
        Finally
            If Not sr1 Is Nothing Then
                sr1.Close()
                sr1.Dispose()
            End If
        End Try
        If bgwLoadList.IsBusy = False Then
        End If
    End Sub

    Private Sub bgwLoadList_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwLoadList.ProgressChanged
        If Not e.UserState Is Nothing Then
            lstboxCast.Items.Add(e.UserState)
            'If lstboxCast.Items.Count = 1 Then lstboxCast.SelectedIndex = 0
        End If
    End Sub

    'Private Delegate Sub addActorDelegate(ByVal actorName As String)
    'Private Sub addActor(ByVal actorName As String)
    '    'some stuff by fatal i only halfway understand, but he said it will make it better :)
    '    'it didn't work :\ so had to take it back out
    '    If Me.InvokeRequired = False Then
    '    Else
    '        Dim u As New addActorDelegate(AddressOf addActor)
    '        Me.Invoke(u, actorName)
    '    End If
    'End Sub

    Private Sub bgwLoadList_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwLoadList.RunWorkerCompleted
        btnGetList.Enabled = True
        Dim ItemCount As String = lstboxCast.Items.Count.ToString
        lblCountItems.Text = ItemCount & " images remaining" 'show remaining actor count from list
        lstboxCast.SelectedIndex = lastIndex
    End Sub

    Public Sub lstboxCast_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstboxCast.SelectedIndexChanged
        'picture boxes are empty unless an item is selected.  load picture using simple http request.
        lastIndex = lstboxCast.SelectedIndex
        Try
            picboxAddImg.Image = Nothing
            picboxAddImg.ImageLocation = String.Empty
            picboxWorkImg.Image = Nothing
            picboxWorkImg.ImageLocation = String.Empty
            btnSubmitImg.Enabled = False
            'label transparency settings for existing image resolution
            lblImgRes.Parent = picboxWorkImg
            lblImgRes.BackColor = Color.FromArgb(125, 0, 0, 0)
            lblImgRes.BringToFront()
            lblImgRes.Location = New Point(15, 125)

            If lstboxCast.SelectedIndex >= 0 Then
                If Regex.IsMatch(lstboxCast.SelectedItem, "[ÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ]") = False Then 'if regex match equals false against special characters, then use standard url
                    picboxWorkImg.ImageLocation = "http://projects.thehtpc.net/ibn/old/" & lstboxCast.SelectedItem & "/folder.jpg"
                    Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(System.Net.HttpWebRequest.Create(picboxWorkImg.ImageLocation).GetResponse().GetResponseStream())
                    lblImgRes.Text = image.Height.ToString & "x" & image.Width.ToString
                    If (image.Width < 200) Or (image.Width > 315) = True Then
                        btnEzAdd.Visible = False
                    ElseIf (image.Height < 300) Or (image.Height > 472) = True Then
                        btnEzAdd.Visible = False
                    ElseIf (image.Height / image.Width < 1.425) Or (image.Height / image.Width > 1.575) = True Then
                        btnEzAdd.Visible = False
                    Else : btnEzAdd.Visible = True
                    End If
                Else
                    Dim myencoding = Encoding.GetEncoding("iso-8859-1") 'if true, then use specified urlencoding
                    picboxWorkImg.ImageLocation = "http://projects.thehtpc.net/ibn/old/" & UrlEncode(lstboxCast.SelectedItem, myencoding) & "/folder.jpg"
                    Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(System.Net.HttpWebRequest.Create(picboxWorkImg.ImageLocation).GetResponse().GetResponseStream())
                    lblImgRes.Text = image.Width.ToString & "x" & image.Height.ToString
                    If (image.Width < 200) Or (image.Width > 315) = True Then
                        btnEzAdd.Visible = False
                    ElseIf (image.Height < 300) Or (image.Height > 472) = True Then
                        btnEzAdd.Visible = False
                    ElseIf (image.Height / image.Width < 1.425) Or (image.Height / image.Width > 1.575) = True Then
                        btnEzAdd.Visible = False
                    Else : btnEzAdd.Visible = True
                    End If
                End If
            End If
            btnSelectImg.Enabled = lstboxCast.SelectedIndex >= 0
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Try
            If SearchGoogleImagesToolStripMenuItem.CheckState = CheckState.Checked Then 'use Google Image search
                Dim str As String
                'str = Chr(34) & UrlEncode(lstboxCast.SelectedItem.ToString) & Chr(34)
                str = UrlEncode(lstboxCast.SelectedItem.ToString)
                WebBrowser1.Navigate("http://www.google.com/images?q=%22" & str & "%22&hl=en&safe=off&biw=1280&bih=935&gbv=2&tbs=isch:1,imgo:1,islt:qsvga,isz:ex,iszw:300,iszh:450,itp:face&source=lnt&sa=X&ei=J_trTL_uEsOblgfF-ujjDw&ved=0CA0QpwU")
            ElseIf SearchYahooImagesToolStripMenuItem.CheckState = CheckState.Checked Then
                Dim str As String
                str = UrlEncode(lstboxCast.SelectedItem.ToString) 'use Yahoo! Image search
                WebBrowser1.Navigate("http://images.search.yahoo.com/search/images?_adv_prop=images&x=op&fr=&_bcrumb=C1a7tR5ZGeA&ei=utf-8&va=&vp=" & str & "&vo=&ve=&imgsz=custom&custom=300x450&vst=0&vs=&vm=r")
            ElseIf SearchBingToolStripMenuItem.CheckState = CheckState.Checked Then
                Dim str As String
                str = Chr(34) & UrlEncode(lstboxCast.SelectedItem.ToString) & Chr(34) 'use Bing! Image search
                WebBrowser1.Navigate("http://www.bing.com/images/search?q=" & str & "+filterui:imagesize-medium+filterui:aspect-tall+filterui:photo-photo+filterui:face-face&sk=&sc=8-0&qpvt=" & str & "&FORM=R5FD15")
            ElseIf SearchPicSearchImagesToolStripMenuItem.CheckState = CheckState.Checked Then
                Dim str As String
                str = UrlEncode(lstboxCast.SelectedItem.ToString) ' use PicSearch image search
                WebBrowser1.Navigate("http://www.picsearch.com/index.cgi?&q=" & str)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnAddImg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddImg.Click
        Try
            If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then 'local file browser
                Dim curImg As Image = Image.FromFile(OpenFileDialog1.FileName())
                If (curImg.Width < 200) Or (curImg.Width > 315) Or (curImg.Height < 300) Or (curImg.Height > 472) Or (curImg.Height / curImg.Width < 1.425) Or (curImg.Height / curImg.Width > 1.575) Then 'checks for proper image dimensions
                    MessageBox.Show("Image dimensions must be within defined limits." & vbCrLf & "Minimum width is 200px.  Minimum height is 300px." & vbCrLf & "Maximum width is 300px.  Maximum height is 450px." & vbCrLf & "Aspect ratio must be within 5% of 1.5 (i.e. 1.425 to 1.575)." & vbCrLf & "Please try another image.")
                    Exit Sub
                ElseIf (OpenFileDialog1.FileName().ToString = "") Then
                    MessageBox.Show("You didn't choose an image.  Please try again.")
                    Exit Sub
                End If
                picboxAddImg.ImageLocation = OpenFileDialog1.FileName
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub picboxAddImg_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles picboxAddImg.DragDrop
        If lstboxCast.Enabled = False Then
            Try
                Dim handle As String() = e.Data.GetData(DataFormats.FileDrop, False) 'get picboxAddImg from browser cache via drag and drop
                If (handle.Length > 0) Then
                    If (System.IO.File.Exists(handle(0))) Then
                        Dim curImg = Image.FromFile(handle(0))
                        If (curImg.Width < 200) Or (curImg.Width > 315) Or (curImg.Height < 300) Or (curImg.Height > 472) Or (curImg.Height / curImg.Width < 1.425) Or (curImg.Height / curImg.Width > 1.575) Then 'checks for proper image dimensions
                            MessageBox.Show("Image dimensions must be within defined limits." & vbCrLf & "Minimum width is 200px.  Minimum height is 300px." & vbCrLf & "Maximum width is 300px.  Maximum height is 450px." & vbCrLf & "Aspect ratio must be within 10% of 1.5 (i.e. 1.425 to 1.575)." & vbCrLf & "Please try another image.")
                        Else
                            picboxAddImg.Image = Image.FromFile(handle(0))
                            picboxAddImg.ImageLocation = handle(0)
                        End If
                    End If
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If
    End Sub

    Private Sub picboxAddImg_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles picboxAddImg.DragEnter
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then 'detect picture entering picture box from drag and drop event
            e.Effect = DragDropEffects.All
        End If
    End Sub

    Private Sub picboxAddImg_LoadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles picboxAddImg.LoadCompleted
        btnSubmitImg.Enabled = True 'enable the submit button once an image is populated in the picbox
    End Sub

    Private Sub btnSelectImg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImg.Click
        If lstboxCast.Enabled = True Then 'select image button just forces an order of events to the user, reducing problems
            btnSelectImg.Text = "Cancel"
            btnAddImg.Enabled = True
            lstboxCast.Enabled = False
            btnGetList.Enabled = False
            pbUpload.Value = 0
        Else
            btnSelectImg.Text = "Select"
            lstboxCast.Enabled = True
            btnAddImg.Enabled = False
            btnGetList.Enabled = Not bgwLoadList.IsBusy
        End If
    End Sub

    Private Sub btnSubmitImg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmitImg.Click
        FTPMkDir() 'create the directory by actor name using module1
        If String.IsNullOrEmpty(picboxAddImg.ImageLocation) = False AndAlso Not picboxAddImg.Image Is Nothing Then
            FTPUpload(lstboxCast.SelectedItem.ToString.ToLower, picboxAddImg.ImageLocation) 'upload picbox image via ftp to created directory
            btnSubmitImg.Enabled = False 'reset interface buttons for next image
            lstboxCast.Enabled = True
            btnGetList.Enabled = True
            btnGetList.PerformClick() 'refresh the list after upload
            btnSelectImg.Text = "Select"
        End If
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Form3.ShowDialog() 'about box
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub btnbrwsBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrwsBack.Click
        WebBrowser1.GoBack()
    End Sub

    Private Sub btnbrwsFwd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrwsFwd.Click
        WebBrowser1.GoForward()
    End Sub

    Private Sub lstboxCast_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstboxCast.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right AndAlso lstboxCast.Enabled = True AndAlso lstboxCast.Items.Count > 0 Then 'right-click context menu for flagging actor items
            lstboxCast.SelectedIndex = lstboxCast.IndexFromPoint(e.X, e.Y)
            ContextMenuStrip1.Show(MousePosition)
        End If
    End Sub

    Private Sub FlagThisEntryToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlagThisEntryToolStripMenuItem.Click
        Dialog1.ShowDialog() ' opens flag item dialog
    End Sub

    Private Sub WebBrowser1_ProgressChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserProgressChangedEventArgs) Handles WebBrowser1.ProgressChanged
        lstboxCast.Focus.Equals(True) 'maintains the focus on the list box
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        txtboxWebBar.Text = e.Url.ToString 'get the current web browser URL to display in address bar
    End Sub

    Private Sub txtboxWebBar_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtboxWebBar.KeyUp
        Try
            If e.KeyCode = Keys.Enter Then 'allows URL to be navigated to after entry into address bar and "Enter" key is pressed
                WebBrowser1.Navigate(txtboxWebBar.Text)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
        Try
            If Not String.IsNullOrEmpty(txtboxWebBar.Text) Then 'browser navigate button
                WebBrowser1.Navigate(txtboxWebBar.Text)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub SearchYahooImagesToolStripMenuItem_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchYahooImagesToolStripMenuItem.CheckStateChanged
        If SearchYahooImagesToolStripMenuItem.Checked = True Then
            SearchBingToolStripMenuItem.Checked = False
            SearchGoogleImagesToolStripMenuItem.Checked = False
            SearchPicSearchImagesToolStripMenuItem.Checked = False
        End If
    End Sub
    Private Sub SearchGoogleImagesToolStripMenuItem_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchGoogleImagesToolStripMenuItem.CheckStateChanged
        If SearchGoogleImagesToolStripMenuItem.Checked = True Then
            SearchBingToolStripMenuItem.Checked = False
            SearchYahooImagesToolStripMenuItem.Checked = False
            SearchPicSearchImagesToolStripMenuItem.Checked = False
        End If
    End Sub

    Private Sub SearchBingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBingToolStripMenuItem.Click
        If SearchBingToolStripMenuItem.Checked = True Then
            SearchGoogleImagesToolStripMenuItem.Checked = False
            SearchYahooImagesToolStripMenuItem.Checked = False
            SearchPicSearchImagesToolStripMenuItem.Checked = False
        End If
    End Sub


    Private Sub SearchPicSearchImagesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchPicSearchImagesToolStripMenuItem.Click
        If SearchPicSearchImagesToolStripMenuItem.Checked = True Then
            SearchBingToolStripMenuItem.Checked = False
            SearchGoogleImagesToolStripMenuItem.Checked = False
            SearchYahooImagesToolStripMenuItem.Checked = False
        End If
    End Sub

    Private Sub btnEzAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEzAdd.Click
        Dialog2.ShowDialog()
    End Sub

End Class
